import { defineStore } from 'pinia';
import { getInfo, login, logout } from '@/api/UserApi';
import { storage } from '@/utils/Storage';
import { TOKEN_KEY } from '@/enums/commEnum';
import { store } from '@/store/index';

interface UserState {
  userInfo?: User;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: undefined,
  }),
  getters: {
    getUserInfo(): User {
      return this.userInfo;
    },
    getPermissions(): string[] {
      return this.userInfo?.permissions || [];
    },
  },
  actions: {
    setUserInfo(info: User) {
      this.userInfo = info;
    },
    login(userInfo: LoginForm) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((result) => {
            let tokenValue = result.data[0].tokenValue;
            storage.set(TOKEN_KEY, tokenValue);
            resolve('');
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    current() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((result) => {
            const vo: User = result.data[0];
            if (!vo.permissions || vo.permissions.length === 0) vo.permissions = ['guest'];
            this.setUserInfo(vo);
            resolve(vo);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    logout() {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            storage.remove(TOKEN_KEY);
            this.userInfo = undefined;
            resolve('');
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    resetToken() {
      return new Promise((resolve) => {
        storage.remove(TOKEN_KEY);
        this.userInfo = undefined;
        resolve('');
      });
    },
  },
});

export function useUserStoreOut() {
  return useUserStore(store);
}
